package cn.aylog.simpleTree;

import java.util.*;

/**
 * 赫夫曼树（wpl： weight path length）最小的树
 * 构建规则：
 * 1、每一个元素都是一个最小二叉树
 * 2、取出2个最小的树，构建成一棵新的二叉树
 * 3、将2个最小的元素删除，将新树加入到原数组
 */
public class HuffmanTreeDemo {
    public static void main(String[] args) {
        int[] arr = {3, 6, 1, 99, 4};
        HuffmanNode huffmanTree = createHuffmanTree(arr);
        System.out.println("前序遍历");
        preOrder(huffmanTree); // 113,14,6,8,4,4,1,3,99
    }


    /**
     * 前序遍历
     */
    public static void preOrder(HuffmanNode root) {
        if (root != null) {
            root.preOrder();
        }
    }

    /**
     * 将给定的数组构建成一个赫夫曼树
     *
     * @param arr 待转换的数组
     * @return 转换后的赫夫曼树的根节点
     */
    public static HuffmanNode createHuffmanTree(int[] arr) {
        // 数组转List<Node>
        List<HuffmanNode> nodes = new ArrayList<>();
        for (int item : arr) {
            nodes.add(new HuffmanNode(item));
        }
        return createHuffmanTree(nodes);
    }
    public static HuffmanNode createHuffmanTree(List<HuffmanNode> nodes) {
        // 数组转List<Node>
        HuffmanNode leftNode, rightNode, parentNode;
        while (nodes.size() > 1) {
            //排序
            Collections.sort(nodes);
            //构建树
            leftNode = nodes.get(0);
            rightNode = nodes.get(1);
            parentNode = new HuffmanNode(leftNode.getValue() + rightNode.getValue());
            parentNode.setLeft(leftNode);
            parentNode.setRight(rightNode);
            // 从原数组去除
            nodes.remove(leftNode);
            nodes.remove(rightNode);
            // 新增节点
            nodes.add(parentNode);
        }
        return nodes.get(0);
    }
}

class HuffmanNode implements Comparable<HuffmanNode> {
    private Integer value;
    private HuffmanNode left;
    private HuffmanNode right;

    public HuffmanNode(Integer value) {
        this.value = value;
    }

    public Integer getValue() {
        return value;
    }

    public HuffmanNode getLeft() {
        return left;
    }

    public void setLeft(HuffmanNode left) {
        this.left = left;
    }

    public HuffmanNode getRight() {
        return right;
    }

    public void setRight(HuffmanNode right) {
        this.right = right;
    }

    @Override
    public int compareTo(HuffmanNode o) {
        return this.value - o.value;
    }

    public void preOrder() {
        System.out.println(this);
        if (this.left != null) this.left.preOrder();
        if (this.right != null) this.right.preOrder();
    }

    @Override
    public String toString() {
        return "HuffmanNode{" +
                "value=" + value +
                '}';
    }
}
